package com.winai.launcher.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ks.projectbasictools.retrofit.HttpResponseListener;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.bean.db.Device;
import com.winai.launcher.bean.requestBean.ScreenSaveBean;
import com.winai.launcher.bean.responseEntity.MojiEntity;
import com.winai.launcher.bean.responseEntity.ScreenSaveEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.HttpUrls;
import com.winai.launcher.manager.DeviceInfoManager;
import com.winai.launcher.manager.ScreenProtectManager;
import com.winai.launcher.manager.WeatherManager;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.utils.ServerUtils;
import com.winai.launcher.utils.WeatherIconUtil;

import java.util.Collections;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * 作者：康少
 * 时间：2019/11/27 0027
 * 说明：屏保
 */
public class ScreenProtectActivity extends BaseActivity {

    @BindView(R.id.cl_header)
    ConstraintLayout includeHeader;
    @BindView(R.id.tv_preview)
    TextView tvPreview;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.banner_background)
    BGABanner bannerBackground;
    @BindView(R.id.str_title)
    TextView strTitle;

    @BindView(R.id.cl_center)
    ConstraintLayout clCenter;
    @BindView(R.id.tv_currentTime)
    TextView tvCurrentTime;
    @BindView(R.id.tv_week)
    TextView tvWeek;
    @BindView(R.id.monthDay)
    TextView monthDay;
    @BindView(R.id.iv_currentWeather)
    ImageView ivCurrentWeather;
    @BindView(R.id.tv_currentLocation)
    TextView tvCurrentLocation;
    @BindView(R.id.tv_currentTemperature)
    TextView tvCurrentTemperature;
    @BindView(R.id.tv_currentWind)
    TextView tvCurrentWind;

    @BindView(R.id.cl_leftBottom)
    ConstraintLayout clLeftBottom;
    @BindView(R.id.tv_currentTime2)
    TextView tvCurrentTime2;
    @BindView(R.id.iv_currentWeather2)
    ImageView ivCurrentWeather2;
    @BindView(R.id.tv_currentLocation2)
    TextView tvCurrentLocation2;
    @BindView(R.id.tv_currentTemperature2)
    TextView tvCurrentTemperature2;
    @BindView(R.id.tv_currentWind2)
    TextView tvCurrentWind2;
    @BindView(R.id.tv_week2)
    TextView tvWeek2;
    @BindView(R.id.monthDay2)
    TextView monthDay2;

    private Context mContext = this;
    /*变量*/
    private AlphaAnimation showAnim, hideAnim;
    private String fromSetCenter;//从设置中心进入
    private boolean isPreviewModel = false;//是否处于预览模式
    private boolean isLocker = false;//锁屏模式

    /**
     * 说明：一分钟监听更新一次UI
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null && action.equals(Intent.ACTION_TIME_TICK)) {
                updateTimeView();
            }
        }
    };

    private boolean isLoaded = false;//屏保是否加载成功
    private NetworkListener mNetworkStateReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_protect);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initListener();
        getHttpData();
        updateViewData();
        updateTimeView();
    }

    private void initObject() {
        showAnim = new AlphaAnimation(0, 1);
        showAnim.setDuration(500);
        hideAnim = new AlphaAnimation(1, 0);
        hideAnim.setDuration(500);

    }

    private void initListener() {
        //时钟广播—— 一分钟更新一次
        IntentFilter filter2 = new IntentFilter();
        filter2.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(receiver, filter2);

        /*监听天气数据变化*/
        GlobalPublisher.setListener(GlobalPublisher.WEATHER_UPDATE, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                updateViewData();
            }
        });
    }

    private void getHttpData() {
        if (!canIn()) {
            return;
        }
        ScreenSaveBean screenSaveBean = new ScreenSaveBean();
        ServerUtils.requestJsonPost(HttpUrls.SCREEN_SAVER, null, screenSaveBean, new HttpResponseListener<ScreenSaveEntity>() {
            @Override
            public void onResponse(ScreenSaveEntity var1, boolean isCache) {
                if (var1 != null && var1.getData() != null) {
                    showEmpty(var1.getData().getScreenSaverVoList() != null && var1.getData().getScreenSaverVoList().size() == 0);
                    initBanner(var1.getData());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable e) {
                /*访问失败，显示空页面*/
                showEmpty(true);
            }

            @Override
            public void onError(int code, String msg) {
                showEmpty(true);
            }
        });
    }

    private long sTime = 0;//请求的时间

    private boolean canIn() {
        //再次请求时间
        long ct = System.currentTimeMillis();
        if (ct - sTime < 2000) {
            LogUtils.d("2s内限制屏保接口请求");
            return false;
        }
        sTime = ct;
        return true;
    }

    private void initBanner(ScreenSaveEntity.DataBean data) {
        bannerBackground.setPageChangeDuration(2000);
        if (!isLocker && ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.DYNAMIC) {
            //设置中心进来
            bannerBackground.setAutoPlayAble(!data.getCarouselSetVo().getRotationTime().equals("0"));
            bannerBackground.setAutoPlayInterval(Integer.parseInt(data.getCarouselSetVo().getRotationTime()) * 1000);
            if (data.getCarouselSetVo().getRotationMode().equals("1")) {
                // 倒序排列
                Collections.reverse(data.getScreenSaverVoList());
            }
        } else if (isLocker && ScreenProtectManager.getModel() == ScreenProtectManager.ScreenProtectModel.DYNAMIC) {
            //屏保锁屏进来
            bannerBackground.setAutoPlayAble(!data.getCarouselSetVo().getRotationTime().equals("0"));
            bannerBackground.setAutoPlayInterval(Integer.parseInt(data.getCarouselSetVo().getRotationTime()) * 1000);
            if (data.getCarouselSetVo().getRotationMode().equals("1")) {
                // 倒序排列
                Collections.reverse(data.getScreenSaverVoList());
            }
        } else {
            bannerBackground.setAutoPlayAble(false);
        }
        bannerBackground.setAdapter(
                (BGABanner.Adapter<ImageView, ScreenSaveEntity.DataBean.ScreenSaverVoListBean>)
                        (banner, itemView, model, position) -> {
                            if (model != null) {
                                PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(
                                        model.getPicturePath()
                                        , itemView);
                            }
                        }
        );
        if ((isLocker && ScreenProtectManager.getModel() == ScreenProtectManager.ScreenProtectModel.STATIC)
                || (!isLocker && ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.STATIC)) {
            //静态屏保，取首张作为屏保
            if (data.getScreenSaverVoList().size() > 0) {
                bannerBackground.setData(Collections.singletonList(data.getScreenSaverVoList().get(0)), null);
            }
        } else if ((isLocker && ScreenProtectManager.getModel() == ScreenProtectManager.ScreenProtectModel.DYNAMIC)
                || (!isLocker && ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.DYNAMIC)) {
            //动态屏保，去掉首张后作为屏保
            if (data.getScreenSaverVoList().size() > 0) {
                data.getScreenSaverVoList().remove(0);
            }
            bannerBackground.setData(data.getScreenSaverVoList(), null);
        }
        bannerBackground.setDelegate(new BGABanner.Delegate() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, @Nullable Object model, int position) {
                if (!isLocker && isPreviewModel) {
                    togglePreview(false);
                } else if (isLocker) {
                    //点一下解锁
                    ScreenProtectActivity.this.finish();
//                    AppManager.getAppManager().finishActivity(ScreenProtectActivity.class);
                    // 更新设备使用状态为 运行
                    DeviceInfoManager.getInstance(mContext).updateDeviceStatus(Device.DeviceStatus.RUNNING);
                }
            }
        });
    }

    private void showEmpty(boolean isShowEmpty) {
        isLoaded = !isShowEmpty;
        ivEmpty.setVisibility(isShowEmpty ? View.VISIBLE : View.GONE);
        if (isShowEmpty) {
            //注册网络监听广播 
            mNetworkStateReceiver = new NetworkListener();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(mNetworkStateReceiver, filter);
        }
    }

    /**
     * 说明：更新视图
     */
    @SuppressLint("SetTextI18n")
    private void updateViewData() {
        MojiEntity mojiEntity = WeatherManager.getInstance(mContext).getMojiEntity();
        if (mojiEntity != null) {
            //城市名
            String cn = mojiEntity.getCity();
            String cityName = cn.replace("市", "");
            tvCurrentLocation.setText(cityName);
            tvCurrentLocation2.setText(cityName);
            //天气图标
            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(WeatherIconUtil.getImgByName(mojiEntity.getCondition().getCondition()), ivCurrentWeather);
            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(WeatherIconUtil.getImgByName(mojiEntity.getCondition().getCondition()), ivCurrentWeather2);
            //气温
            tvCurrentTemperature.setText(mojiEntity.getCondition().getTemp() + "℃");
            tvCurrentTemperature2.setText(mojiEntity.getCondition().getTemp() + "℃");
            //风级
            tvCurrentWind.setText(mojiEntity.getCondition().getWindLevel() + "级风");
            tvCurrentWind2.setText(mojiEntity.getCondition().getWindLevel() + "级风");
        } else {
            WeatherManager.getInstance(mContext).requestWeatherData();
        }
    }

    private void updateTimeView() {
        String ss = BaseUtils.getInitTime();
        String hhmm = BaseUtils.timeStamp2Date(ss, "HH:mm");
        String mmdd = BaseUtils.timeStamp2Date(ss, "yyyy年MM月dd日");
        tvCurrentTime.setText(hhmm);
        tvCurrentTime2.setText(hhmm);
        monthDay.setText(mmdd);
        monthDay2.setText(mmdd);
        tvWeek.setText(BaseUtils.getCurrentDay());
        tvWeek2.setText(BaseUtils.getCurrentDay());
    }

    /**
     * 说明：切换预览模式
     */
    private void togglePreview(boolean isPreview) {
        isPreviewModel = isPreview;
        if (isPreview) {
            includeHeader.setVisibility(View.GONE);
            includeHeader.startAnimation(hideAnim);
            tvPreview.setVisibility(View.GONE);
            tvPreview.startAnimation(hideAnim);
            tvConfirm.setVisibility(View.GONE);
            tvConfirm.startAnimation(hideAnim);
        } else {
            includeHeader.setVisibility(View.VISIBLE);
            includeHeader.startAnimation(showAnim);
            tvPreview.setVisibility(View.VISIBLE);
            tvPreview.startAnimation(showAnim);
            tvConfirm.setVisibility(View.VISIBLE);
            tvConfirm.startAnimation(showAnim);
        }
    }

    /**
     * 作者：康少
     * 时间：2020/3/18 0018
     * 说明：网络监听
     */
    public class NetworkListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (NetworkUtils.hasNetwork(context) && !isLoaded) {
                getHttpData();
            }
        }
    }

    @OnClick({R.id.iv_back_white, R.id.iv_home_white, R.id.tv_preview, R.id.tv_confirm, R.id.view_weather, R.id.view_weather2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back_white:
                finish();
                break;
            case R.id.iv_home_white:
                //模拟HOME
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(intent);
                break;
            case R.id.tv_preview:
                if (!isPreviewModel) {
                    togglePreview(true);
                }
                break;
            case R.id.tv_confirm:
                finish();
                GlobalPublisher.Notify(GlobalPublisher.CHANGE_SCREENPROTECT);
                break;
            case R.id.view_weather:
            case R.id.view_weather2:
                startActivity(new Intent(mContext, WeatherActivity.class));
                finish();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        fromSetCenter = getIntent().getStringExtra("fromSetCenter");
        if (!TextUtils.isEmpty(fromSetCenter) && fromSetCenter.equals("true")) {
            //从设置中心进来
            isLocker = false;
            togglePreview(false);
        } else {
            //锁屏进来
            isLocker = true;
            togglePreview(true);
            //更新设备使用状态为 待机
            DeviceInfoManager.getInstance(mContext).updateDeviceStatus(Device.DeviceStatus.WAITING);

        }
        if (ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.STATIC) {
            strTitle.setText("屏保");
            clCenter.setVisibility(View.VISIBLE);
            clLeftBottom.setVisibility(View.GONE);
        } else if (ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.DYNAMIC) {
            strTitle.setText("动态画报");
            clCenter.setVisibility(View.VISIBLE);
            clLeftBottom.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(receiver);
        } catch (IllegalArgumentException e) {
            //LogUtils.e("捕捉一个crash ScreenProtectActivity unregisterReceiver(receiver)");
        }
        if (mNetworkStateReceiver != null) {
            try {
                unregisterReceiver(mNetworkStateReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                //LogUtils.e("捕捉一个crash：Receiver not registered");
            }
        }
    }
}
